<?php
namespace app\common\service;
use app\common\model\BaseModel;
use app\common\model\CourseModel;
use app\common\model\UserModel;
use app\common\model\UserReqModel;
use think\Image;
class MakeImage{
    /**
     * 处理优惠券
     * @param $money float 金额
     * @param $intro string 描述
     * @return string
     * */
    public static function coupon($money ,$intro="全品类通用")
    {
        $temp_name = 'coupon_temp.jpg';
        $img_path = root_path().'assets/images/'.$temp_name;
        $save_path = "assets/images/coupon/".md5($money.$intro.$temp_name).'.jpg';
        $save_real_path = root_path().$save_path;
        $ttf_path = root_path().'assets/font/PINGFANG_HEAVY.TTF';
        $ttf_path_blod = root_path().'assets/font/PINGFANG_BOLD.TTF';
        if(file_exists($save_real_path)){
            return $save_path;
        }
        $image = Image::open($img_path);
        $width = $image->width();
        $height = $image->height();
        $money_len = mb_strlen($money,'utf8');
        $money_one_width = 30*$money_len;
        $yuan_width = 5;
        $money_total_width = $money_one_width+$yuan_width;
        $money_posx = ($width - $money_total_width)/2 ;
        //元
        $image->text("元",$ttf_path,12,"#ffffff",[$money_posx+$money_total_width-$yuan_width, 75]); //文本
        $posy = 50;
        $image->text($money,$ttf_path_blod,36,"#CC0001",[$money_posx, $posy]); //金额
        $intro_len = mb_strlen($intro,'utf8');
        $intro_arr = [];
        for ($i = 0;$i<$intro_len;$i++){
            array_push($intro_arr, mb_substr($intro,$i,1));
        }
        $intro_str = implode(' ',$intro_arr);
        $intro_one_width = 22;
        $posx = ($width-$intro_len*$intro_one_width)/2;
        $posy = 150;
        $image->text($intro_str,$ttf_path,13,"#FE2C2D",[$posx, $posy]); //文本
        $image->save($save_real_path);
        return '/'.$save_path;
    }

    public static function getImgPath($path,$sign="")
    {
        $file_path = $path;
        if(stripos($path,'http')!==false){
            $host = '/'.app()->request->host().'/';
//            dump(app()->request->host());exit;
            $index = stripos($path,$host);
            if ( $index !== false ) {
                $file_path = substr($file_path,$index+strlen($host));
//                dump($file_path);exit;
            }else{
                $save_path = '/uploads/down_file/'.md5($path.$sign).'.png';
                $file_path = $save_path;
//                echo root_path().$save_path;exit;
                if(file_exists(root_path().$save_path)){

                }else{
                    $arrContextOptions = [
                        'ssl' => [
                            'verify_peer' => false,
                            'verify_peer_name' => false,
                        ]
                    ];
                    file_put_contents(root_path().$save_path,file_get_contents($path,false,stream_context_create($arrContextOptions)));
                }
            }
        }elseif(file_exists($path)){
            return $path;
        }
        return root_path().$file_path;
    }

    public static function generateNewFile($path,$width,$height,$is_round=false)
    {
        $save_path = '/uploads/down_file/'.md5($path.$width.$height.$is_round).'.png';
        if(file_exists(root_path().$save_path)){

        }else{
            $image = Image::open($path);
            //将图片裁剪为300x300并保存为crop.png
            $image->thumb($width, $height,\think\Image::THUMB_SCALING);
            $image->save(root_path().$save_path);
        }

        return root_path().$save_path;
    }

    public static function generateDownFileShareImg(CourseModel $course_model=null,UserModel $user_model=null)
    {
        $shift = '.course_'.sprintf("%06d",$course_model['id']).'.png';
        $temp_file = root_path('assets').'down_file.png';
        $default_user_avatar = root_path('assets').'default_user_avatar.png';
        $req_content = UserModel::getReqContent($user_model);
        $req_content_path = QrCode::generateQrCode('down_file',$req_content,'down_file',100);

        $save_path = $req_content_path.$shift;
//        if(file_exists(root_path().$save_path)){
//            return $save_path;
//        }
        $cover_img = $course_model['cover_img'];
//        dump($cover_img);exit;
//        $img = file_get_contents($course_model);
        $ttf_path = root_path().'assets/font/PINGFANG_HEAVY.TTF';
        $ttf_path_bold = root_path().'assets/font/PINGFANG_BOLD.TTF';

        $image = Image::open($temp_file);
        //课程名
        $course_name = empty($course_model) ? '' : $course_model['name'];
        //封面图
        $course_img = empty($course_model)?'':(empty($course_model['share_img'])?$course_model['cover_img']:$course_model['share_img']);
//        dump($course_img,file_exists($course_img));exit;
        //用户名
        $user_name = empty($user_model)?'登录分享':$user_model['name'];
        //用户头像
        $user_avatar = empty($user_model)?$default_user_avatar:$user_model['avatar'];
        if(!empty($course_img) ){
            $course_img_path = self::getImgPath($course_img,$course_name.$course_model['price'].$user_name.$user_avatar);
            $course_img_path_new = self::generateNewFile($course_img_path,450,450);
            $image->water($course_img_path_new,[35,35]);
        }

        $course_name_arr = [];
        $str_len = 11;
        if(mb_strlen($course_name)<=$str_len){
            $course_name_arr[] = $course_name;
        }else{
            for ($i=0 ; $i<2 ; $i++){
                $sub_str = mb_substr($course_name, $i,$str_len);
                if(!empty($sub_str)){
                    $course_name_arr[] = $sub_str;
                }
            }
        }

        $name_height = count($course_name_arr)>1 ? 500 : 530;
        foreach ($course_name_arr as $key=>$name){
            $image->text($name,$ttf_path,30,"#000000",[40, $name_height+($key*40)]); //文本
        }
        //价格
        $course_price = empty($course_model['price']) ? '免费' : '售价:'.$course_model['price'];
        $image->text($course_price,$ttf_path,18,"#FE7E00",[40,590]); //文本

        //二维码
//        dump(file_exists(root_path().$req_content_path));exit;
        $image->water(root_path().$req_content_path,[370,670]);
        //邀请码
        $user_req_code = empty($user_model)?'???':$user_model['req_code'];
        $image->text($user_req_code,$ttf_path,16,"#A3A3A3",[240,736]); //文本
        //用户名
        $user_name = mb_strlen($user_name) < 10 ? $user_name : $user_name.'...';
        $image->text($user_name,$ttf_path,16,"#000000",[140,700]); //文本

        //用户头像
        $user_avatar = empty($user_model)?$default_user_avatar:$user_model['avatar'];
//        dump($user_avatar);exit;
        if(!empty($user_avatar) ){
            $user_avatar_path = self::getImgPath($user_avatar);
//            dump($user_avatar,$user_avatar_path);
            $user_avatar_path_new = self::generateNewFile($user_avatar_path,80,80,1);
            $image->water($user_avatar_path_new,[35,680]);
        }
//        echo 123;
//        exit;
        $image->save(root_path().$save_path);
        return $save_path;

    }


    public static function makeReqCodeFile($user_id,$content)
    {
        $all_file = self::getdirFile(root_path('assets/qr_code'));
        $exist_file = [];
        foreach ($all_file as $temp_path){
            $file_path_info = pathinfo($temp_path);
            $file_temp_name = $file_path_info['filename']??'req_'.$content;
            $name_info = explode('-',$file_temp_name);
            if(empty($name_info) || !isset($name_info[1]) || count($name_info)<5){
                continue;
            }
            $qr_code_width = $name_info[2];
            $text_location = explode(',',$name_info[3]);
            $water_location = explode(',',$name_info[4]);
            $text_color = $name_info[4]??'000000';
            $text_size = $name_info[5]??'14';
//            dump($file_temp_name,$temp_path,$name_info,$qr_code_width,$text_location,$water_location,$text_color,$text_size);exit;
            if(app()->http->getName()=='master'){
                $qr_code_path = UserModel::generateQrCode($user_id,url('/api/index/down2',['req_code'=>$content],false,true)->build(),'req_code',$qr_code_width,$temp_path);
            }else{
                $qr_code_path = UserModel::generateQrCode($user_id,url('/api/index/reg',['req_code'=>$content],false,true)->build(),'req_code',$qr_code_width,$temp_path);
            }
//            dump($qr_code_path);exit;
            $qr_path_info=pathinfo($qr_code_path);
            $qr_file_name= $qr_path_info['filename']??"qr_code".$user_id;
            $qr_file_ext= $qr_path_info['extension']??"png";
//            dump($file_temp_name);exit;
            $save_path = "uploads/req_code/".$qr_file_name.'-'.$file_temp_name.'.'.$qr_file_ext;
            $save_real_path = root_path().$save_path;
            $ttf_path = root_path().'assets/font/PINGFANG_HEAVY.TTF';
            $ttf_path_blod = root_path().'assets/font/PINGFANG_BOLD.TTF';
            if(file_exists($save_real_path)){
                $exist_file[] = '/'.$save_path;
            }else{
                $image = Image::open($temp_path);
                if($name_info[0]=='yqm'){
                    $content = '邀请码：'.$content;
                }
                //邀请码
                $image->text($content,$ttf_path,$text_size,"#".$text_color,$text_location); //文本
                $image->water(root_path().$qr_code_path,$water_location)->save($save_real_path);
                $exist_file[] = '/'.$save_path;
            }
        }
        return $exist_file;
    }
    public static function getdirFile($path)
    {
        $all_file = [];
        if(!is_dir($path)){
            return $all_file;
        }
        foreach (scandir($path) as $value){
            if($value == '.' || $value == '..'){
                continue;
            }else{
                $all_file[] = $path.$value;
            }
        }
        return $all_file;
    }

    public static function makeDir($path)
    {
        $path = root_path().$path;
        if (!is_dir(dirname($path))) {
            mkdir(dirname($path), 0755, true);
        }
    }
}